from flask import Flask, request, redirect, url_for, render_template, session, g, jsonify
import base64, time, json
from orm import orm
import uuid, math, os
from flask_cors import CORS
from datetime import timedelta

app = Flask(__name__)
CORS(app, supports_credentials=True)
app = Flask(__name__)
app.config['SECRET_KEY'] = 'adsfasfs12345hgfdwertyhn234565432'
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)


def file_name():
    uuid_str = uuid.uuid4()
    tmp_file_name = 'tmpfile_%s.png' % uuid_str
    return tmp_file_name


# 前台图片制作页面
@app.route('/index')
def index():
    uid = session.get('uid', '')
    user_name = session.get('username', '')
    addr = session.get('addr', '')
    if uid and user_name and addr:
        return redirect('/test/index.html')
    else:
        return redirect('/login')


@app.route('/check',methods=['get'])
def check():
    uid = session.get('uid', '')
    user_name = session.get('username', '')
    addr = session.get('addr', '')
    if uid and user_name and addr:
        return '1'
    else:
        return '0'
# 前台登录页面
@app.route('/login', methods=['get', 'post'])
def login():
    if request.method == 'POST':
        uid = request.form.get('code', '')
        username = request.form.get('name', '')
        addr = request.form.get('city', '')
        if uid and username and addr:
            session['uid'] = uid
            session['username'] = username
            session['addr'] = addr
            return redirect('/index')
        else:
            return redirect('/login')

    else:
        return render_template("userLogin.html")


@app.route('/upload', methods=['get', 'post'])
def upload():

    if request.method == 'POST':
        image = request.form.get('img', '')
        if image != '':
            imagedata = base64.b64decode(image)

            localTime = time.localtime(time.time())

            date = time.strftime("%Y-%m-%d", localTime)
            h = time.strftime("%H", localTime)
            uid = session.get('uid', '')
            user_name = session.get('username', '')
            addr = session.get('addr', '')
            if (os.path.exists('img/' + date + '/' + h) == False):
                os.makedirs('img/' + date + '/' + h)
            url = 'img/' + date + '/' + h + '/' +  str(file_name())

            file = open(url, 'wb')
            file.write(imagedata)
            file.close()
            orm.insert_image({'uid': uid, 'user_name': user_name, 'insert_date': date, 'url': url,'addr':addr})
            return json.dumps({'code': 1, 'msg': '上传成功'})
        else:
            json.dumps({'code': 0, 'msg': '请正确使用'})
    else:
        return json.dumps({'code': 0, 'msg': '请正确使用'})


# 后台
@app.route('/admin')
def admin():
    return render_template("admin.html")


# 后台校验
@app.route('/admin_index', methods=['get', 'post'])
def admin_index():
    if request.method == "POST":
        if request.form.get('name', '') == 'admin' and request.form.get('password', '') == 'admin123-123':
            session['username'] = 'admin'
            return redirect('/all')
        else:
            mess = '登录失败'

            return render_template('/admin.html', mess=mess)
    else:
        return redirect(url_for('admin'))


# 后台页面
@app.route('/all')
def hgz():
    p = request.args.get("p", '')  # 页数
    show_shouye_status = 0  # 显示首页状态
    user_name = session.get('username', '')
    if user_name == '':
        return redirect(url_for('admin'))
    if p == '':
        p = 1
    else:
        p = int(p)
        if p > 1:
            show_shouye_status = 1

    image_list = orm.get_image(p)
    all = orm.get_image_all()['num']
    total = int(math.ceil(all / 20.0))
    page = get_page(all, p)
    datas = {
        'list': image_list,

        'p': int(p),
        'total': total,
        'show_shouye_status': show_shouye_status,

        'dic_list': page
    }
    return render_template('/all.html', datas=datas)


@app.route('/times',methods=['get'])
def times():
    user_name = session.get('username', '')
    if user_name == '':
        return redirect(url_for('admin'))
    date = request.args.get("a", '')
    list_times = orm.get_image_all_times(date)

    datas = {
        'list': list_times
    }
    return render_template('/times.html', datas=datas)


def get_page(total, p):
    show_page = 5  # 显示的页码数
    pageoffset = 2  # 偏移量
    start = 1  # 分页条开始
    end = total  # 分页条结束

    if total > show_page:
        if p > pageoffset:
            start = p - pageoffset
            if total > p + pageoffset:
                end = p + pageoffset
            else:
                end = total
        else:
            start = 1
            if total > show_page:
                end = show_page
            else:
                end = total
        if p + pageoffset > total:
            start = start - (p + pageoffset - end)
    # 用于模版中循环
    dic = range(start, end + 1)
    return dic


if __name__ == '__main__':
    app.run()
